#region BSD License
/* 
Copyright (c) 2010, NETFx
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Clarius Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text.RegularExpressions;
using SmartStringResources.CodeDom;

namespace SmartStringResources
{
	public class ResourceFile
	{
		private readonly string _rootArea;
		private readonly CodeDomProvider _provider;
		private readonly GeneratorOptions _options;

		public ResourceFile(string rootArea, CodeDomProvider provider, GeneratorOptions options)
		{
			_rootArea = rootArea;
			_provider = provider;
			_options = options;
		}

		private IEnumerable<ResourceValue> GetResourceValues(TextReader reader)
		{
			var resxReader = new ResXResourceReader(reader) { UseResXDataNodes = true };
			foreach (DictionaryEntry entry in resxReader)
			{
				var dataNode = (ResXDataNode)entry.Value;
				if (dataNode.FileRef == null)
				{
					var value = dataNode.GetValue((ITypeResolutionService)null);
					yield return new ResourceValue(Convert.ToString(entry.Key), Convert.ToString(value));
				}
			}
		}

		public ResourceArea Build(TextReader reader)
		{
			var resourceValues = GetResourceValues(reader);
			return Build(resourceValues);
		}

		private ResourceArea Build(IEnumerable<ResourceValue> resourceValues)
		{
			var root = new ResourceArea { Name = _rootArea, Prefix = "", ValidIdentifierName = _provider.GetValidIdentifier(_rootArea) };
			foreach (var resourceValue in resourceValues)
			{
				int maxAreaParts = int.MaxValue;
				if (_options.MaxAreaDepth.HasValue)
					maxAreaParts = _options.MaxAreaDepth.Value + 1;

				//  Splits: ([resouce area]_)*[resouce name]
				var areaParts = resourceValue.ResourceKey.Split(new[] { '_' }, maxAreaParts, StringSplitOptions.RemoveEmptyEntries);

				if (areaParts.Length <= 1)
				{
					resourceValue.Name = resourceValue.ResourceKey;
					root.Values.Add(resourceValue);
				}
				else
				{
					var area = GetArea(root, areaParts.Take(areaParts.Length - 1));
					resourceValue.Name = areaParts.Skip(areaParts.Length - 1).First();
					area.Values.Add(resourceValue);
				}

				resourceValue.ValidIdentifierName = _provider.GetValidIdentifier(resourceValue.Name);
				resourceValue.ValidIdentifierResourceKey = _provider.GetValidIdentifier(resourceValue.ResourceKey);
				foreach (var formatName in resourceValue.FormatNames)
					formatName.ValidIdentifierName = GetValidParameterName(formatName.Name, resourceValue.FormatNames);
			}

			SortArea(root);

			return root;
		}

		private void SortArea(ResourceArea area)
		{
			area.Values.Sort((left, right) => String.Compare(left.Name, right.Name, StringComparison.Ordinal));
			foreach (var nested in area.NestedAreas)
			{
				SortArea(nested);
			}
		}

		private ResourceArea GetArea(ResourceArea area, IEnumerable<string> areaPath)
		{
			var currentArea = area;
			if (areaPath != null)
			{
				foreach (var areaName in areaPath)
				{
                    var name = GetAreaName(areaName);
                    var existing = currentArea.NestedAreas.FirstOrDefault(a => a.Name == name);
					if (existing == null)
					{
                        if (currentArea.Values.Any(v => v.Name == name))
                            throw new ArgumentException(Properties.Strings.Resources.AreaNameAlreadyInUse(value: name, area: currentArea.Name));

                        existing = new ResourceArea { Name = name, Prefix = currentArea.Prefix + areaName + "_", ValidIdentifierName = _provider.GetValidIdentifier(name) };
						currentArea.NestedAreas.Add(existing);
					}

					currentArea = existing;
				}
			}

			return currentArea;
		}

	    private string GetAreaName(string areaName)
	    {
	        if (string.IsNullOrEmpty(_options.AreaName))
	            return areaName;

	        return _options.AreaName.Replace(GeneratorOptions.AreaNameTemplate, areaName);
	    }

	    private string GetValidParameterName(string name, List<FormatExpression> parameters)
		{
			int argIndex;
			if (int.TryParse(name, out argIndex))
				return GetUniqueParameterName(parameters, string.Concat(Constants.IndexedParameterPrefix, name));

			if (name == Constants.CultureInfoParameterName)
				return GetUniqueParameterName(parameters, name);

			return _provider.GetValidIdentifier(name);
		}

		private string GetUniqueParameterName(List<FormatExpression> parameters, string parameterName)
		{
			while (parameters.Any(p => p.Name == parameterName))
				parameterName = string.Concat(Constants.RepetedParameterPrefix, parameterName);
			return parameterName;
		}
	}
}